package com.leyou.gateway.filter;

import com.leyou.common.auth.entity.PayLoad;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.properties.AllowPathsProperties;
import com.leyou.gateway.properties.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/15 0015
 * Time: 21:19
 */
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {
    @Autowired
    private JwtProperties jwtProp;
    @Autowired
    private AllowPathsProperties allowProp;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 获取当前资源路径
        String requestURI = request.getRequestURI();
        return !isAllowPath(requestURI);
    }

    private boolean isAllowPath(String requestURI) {
        boolean flag = false;
        for (String allowPath : allowProp.getAllowPaths()) {
            if (requestURI.startsWith(allowPath)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public Object run() throws ZuulException {

        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
        try {
            // 获取token
            // 解析token
            PayLoad<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            // 获取用户
            UserInfo userInfo = payLoad.getUserInfo();
            // 获取用户角色 查询权限
            String role = userInfo.getRole();
            // 获取当前资源路径
            String path = request.getRequestURI();
            String method = request.getMethod();
            // TODO 判断权限，此处暂时空置，等待权限服务完成后补充
            log.info("【网关】用户{},角色{}。访问服务{} : {}，", userInfo.getUsername(), role, method, path);
            // 保存用户的Id到请求头
            ctx.addZuulRequestHeader(jwtProp.getUser().getHeaderName(), userInfo.getId().toString());
        } catch (Exception e) {
            // 校验出现异常，返回403 拦截请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
            log.error("非法访问，未登录，地址：{}", request.getRemoteHost(), e);
        }
        return null;
    }
}
